package com.qxt.prize.controllers;

import com.qxt.prize.facades.PrizeFacade;
import com.qxt.prize.forms.PrizeForm;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import top.moirae.repository.PaginationForm;
import top.moirae.rest.AbstractRestResponse;
import top.moirae.rest.ControllerSupport;
import top.moirae.rest.ErrorRestResponse;
import top.moirae.security.HWSession;
import top.moirae.security.forms.IdsForm;
import top.moirae.security.models.Session;

/**
 * @author Chan
 **/
@RestController
@RequestMapping("/prize")
public class PrizeController extends ControllerSupport {
    private final PrizeFacade prizeFacade;

    @Autowired
    public PrizeController(PrizeFacade prizeFacade) {
        this.prizeFacade = prizeFacade;
    }

    @PostMapping
    public AbstractRestResponse create(@HWSession Session session, @RequestBody @Valid PrizeForm.Create form, BindingResult result) {
        if (result.hasErrors()) {
            return ErrorRestResponse.apply(BINDING_ERROR.apply(result));
        }
        return AbstractRestResponse.apply(prizeFacade.create(session, form));
    }

    @GetMapping("/{id}")
    public AbstractRestResponse get(@PathVariable long id) {
        return AbstractRestResponse.apply(prizeFacade.get(id));
    }

    @PutMapping("/{id}")
    public AbstractRestResponse update(@HWSession Session session, @PathVariable Long id, @RequestBody @Valid PrizeForm.Update form, BindingResult result) {
        if (result.hasErrors()) {
            return ErrorRestResponse.apply(BINDING_ERROR.apply(result));
        }
        return AbstractRestResponse.apply(prizeFacade.update(session, id, form));
    }

    @PatchMapping("/{id}")
    public AbstractRestResponse changePublishState(@HWSession Session session, @PathVariable Long id) {
        return AbstractRestResponse.apply(prizeFacade.changePublishState(session, id));
    }

    @DeleteMapping
    public AbstractRestResponse delete(@HWSession Session session, @RequestBody @Valid IdsForm idsForm) {
        return AbstractRestResponse.apply(prizeFacade.delete(session, idsForm));
    }

    @GetMapping
    public AbstractRestResponse list(PrizeForm.Search form, @Valid PaginationForm paginationForm, BindingResult result) {
        if (result.hasErrors()) {
            return ErrorRestResponse.apply(BINDING_ERROR.apply(result));
        }
        return AbstractRestResponse.apply(prizeFacade.list(form, paginationForm));
    }
}

